<?php
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
require_once '/data/web/library/Soooner/Encode/encoder.php';
//require_once 'FtpHelper.php';
/**
 * 主控受控使用的脚本
 * @author Administrator
 *
 */
class proxyncmd{
	private $minicmdpath="";
	private $minicmdwebpath="";
	private $u="bjswaxkjfzyxgs@";
	function miniFun(){
    	$this->minicmdpath = "/data/web/library/Common/Command/";//命令路径
    	$this->minicmdwebpath = "/data/web/public/minicmd/";//命令中使用的web路径
		if (!file_exists($this->minicmdwebpath)){
    			system("mkdir -p ".$this->minicmdwebpath);}//创建路径
	}
    //private $basePath="/data/webroot/minicms/web/public/images/";
	private function db()
    {   
        $params = array ('host' => '127.0.0.1',
                 'port' => '3306',
                 'username' => 'root',
                 'password' => 'soooner.com',
                 'charset' => 'UTF8',
                 'dbname'   => 'minicms');
        $db = Zend_Db::factory('PDO_MYSQL', $params);
        return $db;
    }
    
    private function getConfig()//获取配置信息
    {
    	$db = $this->db();
    	$configrows = $db->fetchAll("select configname, configvalue from config");//获取配置信息
        $configs = array();
    	if (!empty($configrows)){
	       foreach ($configrows as $item){
	          $configs[$item['configname']] = $item['configvalue'];}
    	}//配置信息获取完成
    	return $configs;
    }
	/***
	 * 同步类别
	 */
    public function runsynctypes(){
    	$db = $this->db();
    	//获取config.xml 得到类别列表
    	$config = $this->getConfig();
    	if($config["state"]=="master" && $config["isproxy"]){//代理
    		echo $config["source"]."/iface/config.xml";
    		$xmldata = file_get_contents($config["source"]."/iface/config.xml");    		
    		$doc = new DOMDocument();
			$doc->loadXML($xmldata);
			$items = $doc->getElementsByTagName("navigation");
			foreach($items as $item){
				$type = $item->getAttribute("type");
				$id = $item->getAttribute("id");//类型
				$typename = $item->getAttribute("text");
				$tag1n = $item->getElementsByTagName("class")->item(0)->getAttribute("text");
				$tag2n = $item->getElementsByTagName("class")->item(1)->getAttribute("text");
				$tag3n = $item->getElementsByTagName("class")->item(2)->getAttribute("text");
				$tag1v = $item->getElementsByTagName("class")->item(0)->nodeValue;
				$tag2v = $item->getElementsByTagName("class")->item(1)->nodeValue;
				$tag3v = $item->getElementsByTagName("class")->item(2)->nodeValue;
				$tag1 = $tag1n.":".str_replace("全部|", "", $tag1v);
				$tag2 = $tag2n.":".str_replace("全部|", "", $tag2v);
				$tag3 = $tag3n.":".str_replace("全部|", "", $tag3v);
				$parms = array("id"=>$id,"typename"=>$typename,"model"=>$type,"tag1"=>$tag1,"tag2"=>$tag2,"tag3"=>$tag3,"source"=>$config["source"]."/iiface/export/typeid/$id");
				print_r($parms);
				$insertsql="insert into types(id, typename, model, tag1, tag2, tag3, source)values(:id, :typename, :model, :tag1, :tag2, :tag3, :source)";
				$updatesql="update types set typename=:typename, model=:model, tag1=:tag1, tag2=:tag2, tag3=:tag3, source=:source where id=:id";
				$num=$this->db()->fetchOne("select count(*) c from types where id=:id",array("id"=>$id));
				if($num=="0"){
				  	$db->query($insertsql,$parms);
				}else{
				   	$db->query($updatesql,$parms);
				}
			}
    	}
    }
    /**
     * 同步数据
     * */
    public function runsyncdata($inner=0){
    	$db = $this->db();
    	//需要同步的类型
    	$typesrows = $db->fetchAll("select id, typename, model, source from `types`");
    	foreach($typesrows as $row){//主循环
	    	try{
		    	$xmldata = file_get_contents($row["source"]);
		    	$doc = new DOMDocument();
				$doc->loadXML($xmldata);
				$items = $doc->getElementsByTagName("item");
				if($row["model"]=="live"){//判断栏目类别
					$typeid=$row["id"];//类别编号
					foreach($items as $item){
						$type = $item->getAttribute("type");
						if($type=="live"){//非ipad直播
							$vid = $item->getAttribute("vid");
							$state = $item->getAttribute("state");
							$mark = $item->getAttribute("mark");
							$bitrate = $item->getAttribute("bitrate");
							$duration = $item->getAttribute("duration");
							$title = $item->getElementsByTagName("title")->item(0)->nodeValue;
							$director = $item->getElementsByTagName("director")->item(0)->nodeValue;
							$act = $item->getElementsByTagName("act")->item(0)->nodeValue;
							$imgurl = $item->getElementsByTagName("imgurl")->item(0)->nodeValue;
							$resolution = $item->getElementsByTagName("resolution")->item(0)->nodeValue;
							$epgpath = $item->getElementsByTagName("epgpath")->item(0)->nodeValue;
							$content = $title;//$item->getElementsByTagName("content")->item(0)->nodeValue;
							$playlink = $item->getElementsByTagName("data")->item(0)->getElementsByTagName("playlink")->item(0)->nodeValue;
							$playlinklow = $item->getElementsByTagName("data")->item(0)->getElementsByTagName("playlinklow")->item(0)->nodeValue;
							$tsheader = $item->getElementsByTagName("data")->item(0)->getElementsByTagName("tsheader")->item(0)->nodeValue;
							$key=$typeid."-".$vid;//编号
							//处理数据
							$insertcontentsql="insert into live(title, `type`, sourceimg, mark, bitrate, resolution, content, url, urllow, ists, urltype, `key`, liveip, tsip, ipad,updatetime,epgpath,tsheader)values(:title, :type, :imgurl, :mark, :bitrate, :resolution, :content, :url,:urllow, :ists, :urltype, :key, :liveip, :tsip, :ipad,:updatetime,:epgpath,:tsheader)";
							$updatecontentsql="update live set title=:title, `type`=:type, sourceimg=:imgurl, mark=:mark, bitrate=:bitrate, resolution=:resolution, content=:content, url=:url,urllow=:urllow, ists=:ists, urltype=:urltype, liveip=:liveip, tsip=:tsip, ipad=:ipad ,updatetime=:updatetime, epgpath=:epgpath, tsheader=:tsheader where id=:id";
							$parms = array("title"=>$title, "type"=>$typeid, "imgurl"=>$imgurl, "mark"=>$mark, "bitrate"=>$bitrate, "resolution"=>$resolution, "content"=>$content, "url"=>$playlink,"urllow"=>$playlinklow, "ists"=>"1", "urltype"=>"2", "liveip"=>"1", "tsip"=>"1", "ipad"=>"1","updatetime"=>time(),"epgpath"=>$epgpath,"tsheader"=>$tsheader,"id"=>$vid);
							if($inner)//广电内部使用
								$parms = array("title"=>$title, "type"=>$typeid, "imgurl"=>$imgurl, "mark"=>$mark, "bitrate"=>$bitrate, "resolution"=>$resolution, "content"=>$content, "url"=>$playlink, "ists"=>"0", "urltype"=>"1", "liveip"=>"1", "tsip"=>"1", "ipad"=>"0","updatetime"=>time(),"epgpath"=>$epgpath,"key"=>$key);
							$num=$this->db()->fetchOne("select count(*) c from live where `key`=:key",array("key"=>$key));
							 if($num=="0"){
				            	$db->query($insertcontentsql,$parms);
				            }else{
				            	$db->query($updatecontentsql,$parms);
				            }
						}
					}
				}else{//栏目类别分支
					$typeid=$row["id"];//类别编号
					foreach($items as $item){
						$type = $item->getAttribute("type");
						if($type=="vod"){
							$vid = $item->getAttribute("vid");
							$state = $item->getAttribute("state");
							$mark = $item->getAttribute("mark");
							$bitrate = $item->getAttribute("bitrate");
							$duration = $item->getAttribute("duration");
							$title = $item->getElementsByTagName("title")->item(0)->nodeValue;
							$director = $item->getElementsByTagName("director")->item(0)->nodeValue;
							$act = $item->getElementsByTagName("act")->item(0)->nodeValue;
							$imgurl = $item->getElementsByTagName("imgurl")->item(0)->nodeValue;
							$resolution = $item->getElementsByTagName("resolution")->item(0)->nodeValue;
							$content = $item->getElementsByTagName("content")->item(0)->nodeValue;
							//$playlink = $item->getElementsByTagName("data")->item(0)->getElementsByTagName("playlink");
							$video_list = $item->getElementsByTagName("video_list")->item(0)->getElementsByTagName("video");
							$key=$typeid."-".$vid;//编号
							//处理数据
							$insertcontentsql="insert into vod(title, `type`, director, act,sourceimg, mark, bitrate, resolution, duration, content, vodip, `key`, updatetime)values(:title, :type, :director, :act,:imgurl, :mark, :bitrate, :resolution, :duration, :content, :vodip, :key, :updatetime)";
							$updatecontentsql="update vod set title=:title, `type`=:type, director=:director, act=:act, sourceimg=:imgurl, mark=:mark, bitrate=:bitrate, resolution=:resolution, duration=:duration,content=:content, vodip=:vodip, updatetime=:updatetime where `key`=:key";
							$parms = array("title"=>$title, "type"=>$typeid, "director"=>$director, "act"=>$act ,"imgurl"=>$imgurl, "mark"=>$mark, "bitrate"=>$bitrate, "resolution"=>$resolution, "duration"=>$duration,"content"=>$content, "vodip"=>"1", "updatetime"=>time(), "key"=>$key);
							$row=$this->db()->fetchRow("select	vid from vod where `key`=:key",array("key"=>$key));
							if(!$row){//不存在则插入数据
				            	$db->query($insertcontentsql,$parms);
				            	$contentid = $db->lastInsertId();//节目编号
				            	foreach($video_list as $video){//处理每个video节点
				            		$vlid = $video->getAttribute("vlid");//编号
				            		$vtitle = $video->getElementsByTagName("title")->item(0)->nodeValue;
				            		$vurl = $video->getElementsByTagName("url")->item(0)->nodeValue;
				            		$vkey = $contentid."-".$vlid;
				            		$db->query("insert into vodlist (vid, title, urltype, `key`, source, disabled, updatetime)	values (:vid, :title, :urltype, :key, :source, :disabled, :updatetime)",
				            			array("vid"=>$contentid, "title"=>$vtitle, "urltype"=>"3", "key"=>$vkey, "source"=>$vurl, "disabled"=>"1","updatetime"=>time()));
				            	}
				            	//插入节目
				            }else{//存在，更新数据
				            	$db->query($updatecontentsql,$parms);
				            	$contentid = $row["vid"];
				            	foreach($video_list as $video){//处理每个video节点
				            		$vlid = $video->getAttribute("vlid");//编号
				            		$vtitle = $video->getElementsByTagName("title")->item(0)->nodeValue;
				            		$vurl = $video->getElementsByTagName("url")->item(0)->nodeValue;
				            		$vkey = $contentid."-".$vlid;
				            		$vnum=$this->db()->fetchOne("select count(*) c from vodlist where `key`=:key",array("key"=>$vkey));
				            		if($vnum=="0"){
				            			$db->query("insert into vodlist (vid, title, urltype, `key`, source, disabled,updatetime)	values (:vid, :title, :urltype, :key, :source, :disabled,:updatetime)",
				            				array("vid"=>$contentid, "title"=>$vtitle, "urltype"=>"3", "key"=>$vkey, "source"=>$vurl, "disabled"=>"1", "updatetime"=>time()));
				            		}else{
				            			$db->query("update vodlist set vid=:vid, title=:title, urltype=:urltype, source=:source, updatetime=:updatetime where `key`=:key",
				            				array("vid"=>$contentid, "title"=>$vtitle, "urltype"=>"3", "source"=>$vurl, "updatetime"=>time(), "key"=>$vkey));
				            		}
				            	}
				            }
						}
					}
				}//栏目类别结束
	    	}
	    	catch (Exception $e){
				echo 'Caught exception: ',  $e->getMessage(), "\n";
			}
    	}//主循环结束
    	//删除1小时没有同步的节目
    	$db->query("delete from live where `key`<>'' and updatetime + 3600 < '".time()."'");
    	$db->query("delete from vod where `key`<>'' and updatetime + 3600 < '".time()."'");
    	$db->query("delete from vodlist where `key`<>'' and updatetime + 3600 < '".time()."'");
    }
    

    /**
     * 同步所有图片
     * */
    public function runsyncimg(){
    	$db = $this->db();
    	$num = $db->fetchOne("select count(*) num from live where sourceimg <> oldsourceimg");
    	$vodnum = $db->fetchOne("select count(*) num from vod where sourceimg <> oldsourceimg");
    	if($vodnum>$num)$num=$vodnum;
    	$num = ceil($num/1000);
    	for($i=0; $i<$num; $i++){
    		$this->syncimg();
    	}
    }
    public function runrenewXml(){
    	system("wget http://127.0.0.1/notify/touch/signal/38 -O /dev/null");
    }
    public function runstaticexportXml(){
    	$db = $this->db();
    	$typesrows = $db->fetchAll("select id, typename, model, source from `types`");
    	if(!file_exists("/data/web/public/iface/export")){
    		system("mkdir -p /data/web/public/iface/export");
    	}
    	foreach($typesrows as $row){//主循环
    		$id = $row["id"];
    		system("wget http://127.0.0.1/iiface/export/tag1/%E5%85%A8%E9%83%A8/tag2/%E5%85%A8%E9%83%A8/tag3/%E5%85%A8%E9%83%A8/typeid/$id/$id.xml -O /data/web/public/iface/export/$id.xml");
    		//http://122.193.8.198/iiface/export/tag1/全部/tag2/全部/tag3/全部/typeid/1/1.xml
    	}
    }
 	/**
     * 生成所有uuid
     * */
    public function runsyncuuid(){
    	$db = $this->db();
    	$num = $db->fetchOne("select count(*) num from vodlist where source <> oldsource");
    	$num = ceil($num/1000);
    	for($i=0; $i<$num; $i++){
    		$this->syncuuid();
    	}
    }  
    
    /**
     * 同步图片文件
     * */
    private function syncimg(){
    	//直播图片文件图片保存到/data/web/public/upload/image/ web地址为 /upload/image/
    	$basepath="/data/web/public/upload/image/";
    	$basewebpath="/upload/image/";
    	$db = $this->db();
    	$liverows = $db->fetchAll("select vid,`type`,imgurl,sourceimg,oldsourceimg from live where sourceimg <> oldsourceimg limit 1000");//获取配置信息
    	foreach($liverows as $row){
    		$sourceimg = $row["sourceimg"];//源图片
    		$ext = substr($sourceimg, strrpos($sourceimg, "."));//扩展名
    		$vid = $row["vid"];//编号
    		$hashpath = ceil($vid/1000);
    		$hashpath = "live/".$hashpath."/";//哈希路径
    		if(!file_exists($basepath.$hashpath)){
    			system("mkdir -p ".$basepath.$hashpath);
    		}
    		system("wget ".$sourceimg." -O ".$basepath.$hashpath.$vid.$ext,$result);
    		if($result == "0"){//下载成功
    			echo $vid;
    			$db->query("update live set imgurl=:imgurl,oldsourceimg=sourceimg where vid=:vid",array("imgurl"=>$basewebpath.$hashpath.$vid.$ext,"vid"=>$vid));
    		}
    	}
    	$vodrows = $db->fetchAll("select vid,`type`,imgurl,sourceimg,oldsourceimg from vod where sourceimg <> oldsourceimg limit 1000");//获取配置信息
    	foreach($vodrows as $row){
    		$sourceimg = $row["sourceimg"];//源图片
    		$ext = substr($sourceimg, strrpos($sourceimg, "."));//扩展名
    		$vid = $row["vid"];//编号
    		$hashpath = ceil($vid/1000);
    		$hashpath = "vod/".$hashpath."/";//哈希路径
    		if(!file_exists($basepath.$hashpath)){
    			system("mkdir -p ".$basepath.$hashpath);
    		}
    		system("wget ".$sourceimg." -O ".$basepath.$hashpath.$vid.$ext,$result);
    		if($result == 0){//下载成功
    			$db->query("update vod set imgurl=:imgurl,oldsourceimg=sourceimg where vid=:vid",array("imgurl"=>$basewebpath.$hashpath.$vid.$ext,"vid"=>$vid));
    		}
    	}
    }
    
    //填充uuid
    private function syncuuid(){
    	$basepath="/data/media/";
    	$basewebpath="/media/";
    	$db = $this->db();
    	$filerows = $db->fetchAll("select id,vid, url, source, oldsource from vodlist where oldsource<>source limit 1000");//获取需要更新的数据
    	foreach($filerows as $row){
    		$sourcefile = $row["source"];//源文件
    		$ext = substr($sourcefile, strrpos($sourcefile, "."));//扩展名
    		$id = $row["id"];//编号
    		$vid = $row["vid"];//节目编号
    		//$hashpath = ceil($id/100);
    		//$hashpath = "sync/".$hashpath."/";//哈希路径
    		$uuid = $this->uuid($vid, $sourcefile,true);
    		//system("wget ".$sourcefile." -O ".$basepath.$hashpath.$id.$ext,$result);
    		//if($result == 0){//下载成功
    		$db->query("update vodlist set disabled=0,uuid=:uuid,url=:url,oldsource=source where id=:id",array("uuid"=>$uuid,"url"=>$sourcefile,"id"=>$id));
    		//}
    	}
    }
    //获取uuid,如果是内部拉流服务器，则码率*10
    private function uuid($vid,$url,$isinner=false){
    	$db = $this->db();
    	$url=$this->parseurl($url);
    	$sql = "select bitrate from vod where vid = :vid";
    	if($isinner)
    		$sql = "select bitrate*10 as bitrate from vod where vid = :vid";
    	$bitrate = $db->fetchOne($sql,array("vid"=>$vid));
    	//print_r($bitrate);exit;
    	$str = "[chn]|$url|A|[/chn][ac]||[/ac][pipe]|1|$bitrate|[/pipe][dev]||[/dev][user]|[/user][box][/box]";
    	$rl = new encoder();
    	return $rl->rl_encode($str,1);
    }
	public function parseurl($url="")
	{
		$url = urlencode($url);
		$a = array("%3A", "%2F", "%40");
		$b = array(":", "/", "@");
		$url = str_replace($a, $b, $url);
		return $url;
	}
}
$cmd=$argv[1]; 
if($cmd=="data"){
	$command = new proxyncmd();
	$command->runsynctypes();
	$command->runsyncdata();
	$command->runsyncimg();
	$command->runsyncuuid();
	$command->runrenewXml();
	syslog(LOG_INFO, ": commands - syncmd.runsyncdata");
}
